package com.se7en.ufutil;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.AdapterView.OnItemSelectedListener;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;



public class MainViewController extends MapActivity implements OnClickListener {
	private StudyArea studyArea;
	private FloorPlan floorPlan;
	private Trash trash;
	private Dining dining;
	private DataAccess dataAccess;
	private Parking parking;
	private Overlay activeOverlay;
	private MapView theMapView;
	private MapController mapController;
	private SharedPreferences mPrefs;
	private GatorLocationOverlay myLocationOverlay;
	private Integer currentOverlay;
	private boolean[] parkingDisplay;

	Button searchButton;
	EditText searchBar; 
	Button parkingButton;
	Button cenGPS;
	Button cenCampus;
	Spinner s;
	String selBldg;

	int idea;
	ImageView iv;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.main);


		//Paul: getting saved preferences
		mPrefs = getSharedPreferences("prefs", 0);


		idea = mPrefs.getInt("first start", 1);
		iv =  (ImageView) findViewById(R.id.imageView1);
		
		if (idea == 8) {
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
		} else {
			iv.setClickable(true);
			iv.setVisibility(View.VISIBLE);
			idea=1;
			}
		
			iv.setOnClickListener(new View.OnClickListener(){
				public void onClick(View v) {
					Log.v("PAUL", " click");
					switch (idea) {
					case 0:
						iv.setImageResource(R.drawable.tut0);
						idea++;
						break;
					case 1:
						iv.setImageResource(R.drawable.tut1);
						idea++;
						break;
					case 2:
						iv.setImageResource(R.drawable.tut2);
						idea++;
						break;
					case 3:
						iv.setImageResource(R.drawable.tut3);
						idea++;
						break;
					case 4:
						iv.setImageResource(R.drawable.tut4);
						idea++;
						break;
					case 5:
						iv.setImageResource(R.drawable.tut5);
						idea++;
						break;
					case 6:
						iv.setImageResource(R.drawable.tut6);
						idea++;
						break;
					case 7:
						iv.setImageResource(R.drawable.tut7);
						idea++;
						break;
					case 8:
						iv.setVisibility(View.INVISIBLE);
						iv.setClickable(false);

						break;
					default:
						break;
					}
				}
			});
		 

		//Set up map view and location manager/listener
		theMapView = (MapView) findViewById(R.id.themap);
		theMapView.setBuiltInZoomControls(true);
		mapController = theMapView.getController();



		//Create singleton objects
		dataAccess = new DataAccess(this);
		dataAccess.open();
		studyArea = new StudyArea(this.getResources().getDrawable(R.drawable.green_dot_icon), theMapView.getContext(), dataAccess, theMapView);
		parking = new Parking(this.getResources().getDrawable(R.drawable.green_dot_icon), theMapView.getContext(), dataAccess, theMapView);
		dining = new Dining(this.getResources().getDrawable(R.drawable.green_dot_icon), theMapView.getContext(), dataAccess, theMapView);
		trash = new Trash(theMapView.getContext(), dataAccess);
		floorPlan = new FloorPlan(this.getResources().getDrawable(R.drawable.green_dot_icon), theMapView.getContext(), dataAccess, theMapView);

		//buttons for Classroom search
		searchButton = (Button) findViewById(R.id.SearchButton);
		searchBar = (EditText) findViewById(R.id.searchBar);
		s = (Spinner) findViewById(R.id.MVtextBldg);
		searchButton.setVisibility(View.GONE); // turn off search button visibility in initialization
		searchBar.setVisibility(View.GONE);
		s.setVisibility(View.GONE);
		searchButton.setOnClickListener(this);
		//buttons for Parking filter
		parkingButton = (Button) findViewById(R.id.ParkingButton);
		parkingButton.setVisibility(View.GONE);
		parkingButton.setOnClickListener(this);
		cenGPS = (Button) findViewById(R.id.toGPS);
		cenGPS.setOnClickListener(this);
		cenCampus = (Button) findViewById(R.id.toCamp);
		cenCampus.setOnClickListener(this);

		//Starting up the location overlay
		myLocationOverlay = new GatorLocationOverlay(this, theMapView);


		//Paul: attempting to fix the fact that overlays are reset when orientation is changed.
		Integer saved = (Integer) getLastNonConfigurationInstance();
		if (saved == null) {
			saved = mPrefs.getInt("saved_overlay", 5);
			//setting the starting point for the map to start up at
			GeoPoint startingPoint = new GeoPoint(29648615, -82344128);
			mapController.setZoom(17);
			mapController.setCenter(startingPoint);
		}
		switch (saved.intValue()) {
		case 1:
			currentOverlay = 1;
			setOverlay(floorPlan);
			searchButton.setVisibility(View.VISIBLE);
			searchBar.setVisibility(View.VISIBLE);
			s.setVisibility(View.VISIBLE);
			break;
		case 2:
			currentOverlay = 2;
			setOverlay(dining);
			break;
		case 3:
			currentOverlay = 3;
			setOverlay(parking);
			parkingButton.setVisibility(View.VISIBLE);
			break;
		case 4:
			currentOverlay = 4;
			setOverlay(studyArea); 
			break;
		case 5:
			currentOverlay = 5;
			setOverlay(trash);
			break;

		default:
			currentOverlay = 5;
			setOverlay(trash);
			break;
		}



		class BldgSelectedListener implements OnItemSelectedListener {

			public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
				selBldg=parent.getItemAtPosition(pos).toString();
				Log.v("PAUL", selBldg);
				//textRm.setText("");
				//textRm.requestFocus();
			}

			public void onNothingSelected(AdapterView<?> parent) {
				// Do nothing.
			}
		}



		s.setAdapter(DataAccess.getBldgAdapter(this.getBaseContext()));
		s.setOnItemSelectedListener(new BldgSelectedListener());
		int spinnerPosition = 0;

		//set the default according to value
		s.setSelection(spinnerPosition);
		selBldg="CISE";

		//Initialize parkingDisplay
		parkingDisplay = new boolean[7];
		for (Integer i = 0; i < parkingDisplay.length; i++) {
			Log.v("PAUL", i.toString());
			parkingDisplay[i] = mPrefs.getBoolean(i.toString(), true);

		}
		parking.resetOverlay(parkingDisplay);
	}

	@Override
	protected void onResume() {
		super.onResume();
		myLocationOverlay.enableMyLocation();
	}

	//Paul: saving current Overlay when user exits
	@Override
	protected void onPause() {
		super.onPause();
		Log.v("PAUL", "onPause is called");
		SharedPreferences.Editor ed = mPrefs.edit();
		ed.putInt("saved_overlay", currentOverlay.intValue());
		ed.putBoolean("0", parkingDisplay[0]);
		ed.putBoolean("1", parkingDisplay[1]);
		ed.putBoolean("2", parkingDisplay[2]);
		ed.putBoolean("3", parkingDisplay[3]);
		ed.putBoolean("4", parkingDisplay[4]);
		ed.putBoolean("5", parkingDisplay[5]);
		ed.putBoolean("6", parkingDisplay[6]);
		ed.putInt("first start", idea);
		ed.commit();


		myLocationOverlay.disableMyLocation();
	}


	//Paul: saving current Overlay for phone rotation
	@Override
	public Object onRetainNonConfigurationInstance() {
		// TODO Auto-generated method stub
		final Integer saving = currentOverlay;
		return saving;
	}

	//Paul: To fix an error with the Override go to 
	//Window->Preferences(Eclipse->Preferences for mac)->Java->Compiler
	//make sure it's set to 1.6 or higher here and in the "Project Specific Settings" link towards the top of this window
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.SearchButton:
			String searchValue = ((EditText) findViewById(R.id.searchBar)).getText().toString().trim().toUpperCase();
			Log.v("PAUL", searchValue);
			floorPlan.search(selBldg, searchValue);  
			break;
		case R.id.ParkingButton:
			//show the parking filter dialog
			if (activeOverlay instanceof BalloonItemizedOverlay ) {
				@SuppressWarnings("unchecked")
				BalloonItemizedOverlay<OverlayItem> test = (BalloonItemizedOverlay<OverlayItem>) activeOverlay;
				test.hideBalloon();                     
			}
			showParkingFilter();
			break;
		case R.id.toGPS:
			//Center on GPS Location
			Log.v("PAUL", "Clicked on cntrGPS");
			if ( myLocationOverlay.isMyLocationEnabled() && myLocationOverlay.getMyLocation() != null){
				mapController.animateTo(myLocationOverlay.getMyLocation());

			}
			break;
		case R.id.toCamp:
			//Center on Campus
			Log.v("PAUL", "Clicked on cntrCampus");
			mapController.animateTo(new GeoPoint(29648615, -82344128));
			break;

		default:
			break;
		}   
	}

	//Sweet new parking filter
	private void showParkingFilter() {
		//Names of the choices
		final CharSequence[] items = {"Carpool Decal", "Gated Decal", "Green Decal",
				"Orange Decal", "Red 1 Decal", "Reserved", "Scooter Decal"};
		//Let's build a sweet dialog!
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("Parking Filter");

		builder.setMultiChoiceItems(items, parkingDisplay,
				new DialogInterface.OnMultiChoiceClickListener() {
			public void onClick(DialogInterface dialog, int whichButton, boolean isChecked) {
				//Update any choice changes to the selection
				if(isChecked) parkingDisplay[whichButton] = true;
				else{ parkingDisplay[whichButton] = false; }
			}
		}
				);
		//Gots to have an accept button, no?
		builder.setPositiveButton("Accept",
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				//Take the selections and update parking!
				parking.resetOverlay(parkingDisplay);
				//Forces the map to redraw so the map updates without the user having to do so
				theMapView.invalidate();
			}
		}
				);
		AlertDialog parkingDialog = builder.create();
		parkingDialog.show();
		//Fiddlin with the size and whathaveyou
		//Does not work with landscape orientation, taking out for now.
		/*WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
            lp.copyFrom(parkingDialog.getWindow().getAttributes());
            lp.width = 400;
            lp.height = 640;
            lp.x=0;
            lp.y=0;
            parkingDialog.getWindow().setAttributes(lp);*/
	}


	public void setOverlay(Overlay newOverlay) {
		//clears any active overlays and then adds new overlay
		if(activeOverlay == newOverlay) return;
		//Paul: Currently removes all overlays in order to get rid of balloons :(
		theMapView.getOverlays().clear();
		if (activeOverlay instanceof BalloonItemizedOverlay ) {
			@SuppressWarnings("unchecked")
			BalloonItemizedOverlay<OverlayItem> test = (BalloonItemizedOverlay<OverlayItem>) activeOverlay;
			test.hideBalloon();                     
		}

		activeOverlay = newOverlay;
		theMapView.getOverlays().add(activeOverlay);
		theMapView.getOverlays().add(myLocationOverlay);
		//Paul: causes mapview to refresh and therefore draw the new overlay, 
		//not sure if there's a better way
		theMapView.invalidate();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.mainmenu, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		//Paul: Switch case statement to find which menu button has been pressed.

		switch (item.getItemId()) {
		case R.id.classrooms:
			currentOverlay = 1;
			setOverlay(floorPlan);
			searchButton.setVisibility(View.VISIBLE);
			searchBar.setVisibility(View.VISIBLE);  
			parkingButton.setVisibility(View.GONE);
			s.setVisibility(View.VISIBLE);
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
			return true;
		case R.id.eat: 
			currentOverlay = 2;
			setOverlay(dining);
			searchButton.setVisibility(View.GONE);
			searchBar.setVisibility(View.GONE);
			parkingButton.setVisibility(View.GONE);
			s.setVisibility(View.GONE);
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
			return true;
		case R.id.parking: 
			currentOverlay = 3;
			setOverlay(parking); 
			searchButton.setVisibility(View.GONE);
			searchBar.setVisibility(View.GONE);
			parkingButton.setVisibility(View.VISIBLE);
			s.setVisibility(View.GONE);
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
			return true;
		case R.id.study: 
			currentOverlay = 4;
			setOverlay(studyArea); 
			searchButton.setVisibility(View.GONE);
			searchBar.setVisibility(View.GONE);
			parkingButton.setVisibility(View.GONE);
			s.setVisibility(View.GONE);
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
			return true;
		case R.id.trash: 
			currentOverlay = 5;
			setOverlay(trash);
			searchButton.setVisibility(View.GONE);
			searchBar.setVisibility(View.GONE);
			parkingButton.setVisibility(View.GONE);
			s.setVisibility(View.GONE);
			iv.setVisibility(View.INVISIBLE);
			iv.setClickable(false);
			return true;
			
		case R.id.tutorial:
			idea=0;
			iv.setImageResource(R.drawable.tut0);
			iv.setVisibility(View.VISIBLE);
			iv.setClickable(true);
			return true;


		default:
			return false;
		}

	}

	// Adlai: This function is required to be implemented in order to conform to the Google Maps TOS
	// We don't ever display directions, so this can just always be false.
	public boolean isRouteDisplayed()
	{
		return false;
	}
}
